package scau.gsmg.misp.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.IMenuDao;
import scau.gsmg.misp.vo.Permission;
import scau.gsmg.misp.vo.Role;
import scau.gsmg.misp.vo.RolePermission;
import scau.gsmg.misp.vo.UserRole;

/**
 * @Title: MenuDAO.java
 * @Group: GaoShenMenGui
 * @Author: WXY
 * @Date: 2015-6-4
 */
@Repository
public class MenuDAO extends BaseDAO implements IMenuDao {

	/**
	 * 菜单树
	 */
	@Override
	public List<Permission> searchMenu(int loginID) {
		// TODO Auto-generated method stub
		Session session = getSession();
		List<Permission> permission = new ArrayList<Permission>();
		try {
			String hqlRole = "from UserRole where user.id=?";// 根据登陆号来找到这位用户所拥有的角色
			Query queryRole = session.createQuery(hqlRole);
			queryRole.setParameter(0, loginID);
			List<UserRole> userRole = queryRole.list();
			if (userRole.size() != 0) {
				for (UserRole ur : userRole) {
					String hqlRolePer = "from RolePermission where role.id=?";// 根据角色id来找到这角色所有权限
					Query queryRolePer = session.createQuery(hqlRolePer);
					queryRolePer.setParameter(0, ur.getRole().getId());
					List<RolePermission> rolePer = queryRolePer.list();
					if (rolePer.size() != 0) {
						for (RolePermission rp : rolePer) {
							Permission p = rp.getPermission();
							if ("F".equals(p.getType())
									|| "N".equals(p.getType())) {// 属于菜单类型的权限的处理
								if (permission.size() == 0
										|| !isExsit(permission, p.getId())) {// 如果permission为null或F、N没有加入permission，将F、N加入permission
									permission.add(p);
								}
								if (p.getSort() != null
										&& !"".equals(p.getSort())) {// 如果存在父节点
									Permission ps = getParent(Integer.valueOf(p
											.getSort()));
									if (!isExsit(permission, ps.getId()))
										permission.add(ps);// 加入父节点
								}

							} else {// 功能的
								if ("O".equals(p.getType())
										&& p.getPid() != null) {// 功能O的处理
									Permission ps = getParent(p.getPid());
									if (permission.size() == 0
											|| !isExsit(permission, ps.getId())) {// 存在父节点且父节点没有加入permission
										permission.add(ps);// 加入父节点
										if (ps.getSort() != null
												&& !"".equals(ps.getSort())) {// 判断父节点是否还有父节点
											Permission pp = getParent(Integer
													.valueOf(ps.getSort()));
											if (!isExsit(permission, pp.getId()))
												permission.add(pp);// 加入父节点的父节点
										}
									}
									if(!isExsit(permission, p.getId())){
										permission.add(p);
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：searchMenu" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return permission;
	}

	/**
	 * 权限的分配
	 */
	@Override
	public List distributePermission(int role) {
		Session session = getSession();
		List dataList = new ArrayList();
		try {
			String hql = "from RolePermission where role.id=?";// 根据角色来查找角色权限
			Query query = session.createQuery(hql);
			query.setParameter(0, role);
			List<RolePermission> list = query.list();
			List<Permission> listPer = null;
			for (RolePermission pr : list) {
				if (listPer == null) {
					listPer = new ArrayList<Permission>();
				}
				listPer.add(pr.getPermission());// 将Permission加入到listper，拥有的权限
			}
			List<Permission> listMenu = getAllMenu();// 获取所有的树的内容
			for (Permission p : listMenu) {// 遍历树，在遍历所拥有的权限，如果将增删改查加入树的permission中
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", p.getId());
				jsonMap.put("region", p.getName());
				if (p.getSort() != null) {
					jsonMap.put("_parentId", p.getSort());
				}
				if (listPer != null) {// 如果拥有权限
					for (Permission per : listPer) {
						if ("N".equals(p.getType())) {// N将1.2.3.4.browse设为没有
							jsonMap.put("1", "d");
							jsonMap.put("2", "d");
							jsonMap.put("3", "d");
							jsonMap.put("4", "d");
							jsonMap.put("browse", "d");
							if (p.getId() == per.getId()) {
								jsonMap.put("5" + "", "P");
							}
						} else {// 将非N的5设为没有
							jsonMap.put("5", "d");
							if (p.getId() == per.getId()) {
								jsonMap.put("browse", "P");
							}
							if (p.getId() == per.getPid()) {
								jsonMap.put(per.getSort() + "", "P");
							}
						}
					}
				} else {// 权限树为空时的设置
					if ("N".equals(p.getType())) {
						jsonMap.put("1", "d");
						jsonMap.put("2", "d");
						jsonMap.put("3", "d");
						jsonMap.put("4", "d");
						jsonMap.put("browse", "d");
					} else {
						jsonMap.put("5", "d");
					}

				}
				dataList.add(jsonMap);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：distributePermission" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return dataList;
	}

	/**
	 * @Description:获取所有目录树的内容
	 */
	private List getAllMenu() {
		Session session = getSession();
		List<Permission> list = null;
		String hql = "from Permission where type='F' or type='P' or type='N'";
		try {
			Query query = session.createQuery(hql);
			list = query.list();
			System.out.println("List<Permission>" + list.size());
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：getAllMenu" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return list;
	}

	/**
	 * @Description:根据pid获取节点的内容
	 */
	private Permission getParent(int pid) {
		Session session = getSession();
		String hql = "from Permission where id=?";
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, pid);
			List<Permission> per = query.list();
			if (per.size() != 0) {
				for (Permission p : per) {
					session.close();
					return p;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：getParent" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return null;
	}

	/**
	 * 判断per中是否存在
	 */
	private boolean isExsit(List<Permission> per, int parameter) {
		for (Permission p : per) {
			if (p.getId() == parameter) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 修改角色权限
	 */
	@Override
	public boolean editPermission(int role, int id, int sort) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		String hql = "from Permission where pid=? and sort=?";
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, id);
			query.setParameter(1, sort + "");
			List<Permission> per = query.list();
			for (Permission p : per) {
				boolean editPermission = editRolePermission(role, p.getId());
				flag = editPermission;
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：editPermission" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return flag;
	}

	/**
	 * 写入RolePermission数据库
	 */
	@Override
	public boolean editRolePermission(int role, int id) {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			Transaction tx = session.beginTransaction();
			RolePermission rp = new RolePermission();
			Role r = new Role();
			r.setId(role);
			Permission p = new Permission();
			p.setId(id);
			rp.setRole(r);
			rp.setPermission(p);
			session.save(rp);//
			tx.commit();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("捕获异常：editPermission" + e);
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return flag;
	}

	/**
	 * 根据role。id删除RolePermission
	 */
	@Override
	public boolean deleteAll(int role) {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try {
			String hql = "delete RolePermission rp where rp.role.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, role);
			query.executeUpdate();
			tx.commit();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return flag;
	}

	@Override
	public List showPermission(int id) {
		List<Permission> per = searchMenu(id);
		List dataList = new ArrayList();
		for (Permission p : per) {
			System.out.println("uu" + p.getId() + p.getPid() + p.getName() + p.getDescription());
			HashMap<String, Object> jsonMap = new HashMap<String, Object>();
			jsonMap.put("id", p.getId()); 
			if (p.getPid()!=null&&p.getPid()!=5) {
				jsonMap.put("_parentId", p.getPid()); 
			} 
			if("F".equals(p.getType())||"N".equals(p.getType())){
				jsonMap.put("_parentId", p.getSort()); 
			} 
			jsonMap.put("region",p.getName()); 
			jsonMap.put("description", p.getDescription());
			dataList.add(jsonMap); 
		} 
		return dataList;
	}

}
